package cn.hj.domain.strategy.service.rule.tree.impl;

import cn.hj.domain.strategy.adapter.repository.IStrategyRepository;
import cn.hj.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import cn.hj.domain.strategy.service.rule.tree.ILogicTreeNode;
import cn.hj.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 *
 */
@Component("rule_lock")
@Slf4j
public class RuleLockLogicTreeNode implements ILogicTreeNode {

    @Resource
    private IStrategyRepository strategyRepository;


    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue, Date endDateTime) {

        log.info("规则过滤-次数锁 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
        long raffleCount = 0L;
        try {
            raffleCount = Long.parseLong(ruleValue);
        } catch (Exception e) {
            throw new RuntimeException("规则过滤-次数锁异常 ruleValue: " + ruleValue + " 配置不正确");
        }

        Integer userRaffleCount = strategyRepository.queryTodayUserRaffleCount(strategyId, userId);

        //用户抽奖次数大于规则限定数，规则放行。
        if (userRaffleCount >= raffleCount) {
            log.info("用户抽奖次数大于规则限定数，规则放行，当前抽奖次数{}", userRaffleCount);
            return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
                    .build();
        }
        //用户抽奖次数小于规则限定数，规则拦截。
        log.info("用户抽奖次数小于规则限定数，规则拦截，当前抽奖次数{}", userRaffleCount);
        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                .build();


    }
}
